#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
搜狐号自动保存草稿程序
支持动态替换标题、摘要、正文内容
"""

import requests
import json
import time
from urllib.parse import urlencode
from typing import Dict, Any, Optional
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('sohu_draft.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

class SohuDraftPublisher:
    """搜狐号草稿发布器"""
    
    def __init__(self, config_file: str = 'sohu_config.json'):
        """初始化发布器
        
        Args:
            config_file: 配置文件路径
        """
        self.config = self._load_config(config_file)
        self.session = requests.Session()
        self._setup_session()
    
    def _load_config(self, config_file: str) -> Dict[str, Any]:
        """加载配置文件"""
        try:
            with open(config_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            logger.error(f"配置文件 {config_file} 不存在")
            raise
        except json.JSONDecodeError:
            logger.error(f"配置文件 {config_file} 格式错误")
            raise
    
    def _setup_session(self):
        """设置请求会话"""
        headers = {
            'accept': '*/*',
            'accept-encoding': 'gzip, deflate, br, zstd',
            'accept-language': 'zh-CN,zh;q=0.9',
            'connection': 'keep-alive',
            'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'host': 'mp.sohu.com',
            'origin': 'https://mp.sohu.com',
            'referer': 'https://mp.sohu.com/mpfe/v4/contentManagement/news/addarticle?contentStatus=1',
            'sec-ch-ua': '"Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"macOS"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36',
            'x-requested-with': 'XMLHttpRequest'
        }
        
        # 设置Cookie
        if 'cookie' in self.config:
            headers['cookie'] = self.config['cookie']
        
        self.session.headers.update(headers)
    
    def save_draft(self, title: str, brief: str, content: str, 
                   draft_id: Optional[str] = None) -> Dict[str, Any]:
        """保存草稿
        
        Args:
            title: 文章标题
            brief: 文章摘要
            content: 文章正文（HTML格式）
            draft_id: 草稿ID（可选，用于更新现有草稿）
        
        Returns:
            API响应结果
        """
        # 构建请求URL
        account_id = self.config.get('account_id', '121905676')
        url = f"https://mp.sohu.com/mpbp/bp/news/v4/news/draft?accountId={account_id}"
        
        # 构建表单数据
        form_data = {
            'title': title,
            'brief': brief,
            'content': content,
            'channelId': self.config.get('channel_id', 31),
            'categoryId': self.config.get('category_id', -1),
            'userColumnId': self.config.get('user_column_id', 0),
            'columnNewsIds': self.config.get('column_news_ids', ''),
            'businessCode': self.config.get('business_code', 0),
            'isOriginal': self.config.get('is_original', False),
            'cover': self.config.get('cover', ''),
            'attrIds': self.config.get('attr_ids', ''),
            'topicIds': self.config.get('topic_ids', ''),
            'userLabels': json.dumps(self.config.get('user_labels', []), ensure_ascii=False),
            'isAd': self.config.get('is_ad', 0),
            'reprint': self.config.get('reprint', False),
            'customTags': self.config.get('custom_tags', ''),
            'infoResource': self.config.get('info_resource', 0),
            'sourceUrl': self.config.get('source_url', ''),
            'visibleToLoginedUsers': self.config.get('visible_to_logined_users', 0),
            'accountId': account_id
        }
        
        # 如果提供了草稿ID，添加到表单数据中
        if draft_id:
            form_data['id'] = draft_id
        
        try:
            logger.info(f"开始保存草稿: {title}")
            
            # 发送POST请求
            response = self.session.post(url, data=form_data, timeout=30)
            response.raise_for_status()
            
            # 解析响应
            result = response.json()
            
            if result.get('status') == 'success' or response.status_code == 200:
                logger.info(f"草稿保存成功: {title}")
                return {
                    'success': True,
                    'message': '草稿保存成功',
                    'data': result
                }
            else:
                logger.error(f"草稿保存失败: {result}")
                return {
                    'success': False,
                    'message': f"草稿保存失败: {result.get('message', '未知错误')}",
                    'data': result
                }
                
        except requests.exceptions.RequestException as e:
            logger.error(f"网络请求错误: {e}")
            return {
                'success': False,
                'message': f"网络请求错误: {e}",
                'data': None
            }
        except json.JSONDecodeError as e:
            logger.error(f"响应解析错误: {e}")
            return {
                'success': False,
                'message': f"响应解析错误: {e}",
                'data': None
            }
        except Exception as e:
            logger.error(f"未知错误: {e}")
            return {
                'success': False,
                'message': f"未知错误: {e}",
                'data': None
            }
    
    def batch_save_drafts(self, articles: list, delay: int = 2) -> list:
        """批量保存草稿
        
        Args:
            articles: 文章列表，每个元素包含title, brief, content
            delay: 请求间隔时间（秒）
        
        Returns:
            保存结果列表
        """
        results = []
        
        for i, article in enumerate(articles, 1):
            logger.info(f"处理第 {i}/{len(articles)} 篇文章")
            
            result = self.save_draft(
                title=article['title'],
                brief=article['brief'],
                content=article['content'],
                draft_id=article.get('draft_id')
            )
            
            results.append({
                'index': i,
                'title': article['title'],
                'result': result
            })
            
            # 添加延迟，避免请求过于频繁
            if i < len(articles):
                time.sleep(delay)
        
        return results

def main():
    """主函数示例"""
    try:
        # 创建发布器实例
        publisher = SohuDraftPublisher()
        
        # 示例文章数据
        sample_articles = [
            {
                'title': '测试标题1',
                'brief': '这是一个测试摘要1...',
                'content': '<p>这是测试正文内容1</p>'
            },
            {
                'title': '测试标题2',
                'brief': '这是一个测试摘要2...',
                'content': '<p>这是测试正文内容2</p>'
            }
        ]
        
        # 单篇保存示例
        result = publisher.save_draft(
            title="单篇测试标题",
            brief="单篇测试摘要",
            content="<p>单篇测试正文</p>"
        )
        print(f"单篇保存结果: {result}")
        
        # 批量保存示例
        # batch_results = publisher.batch_save_drafts(sample_articles)
        # print(f"批量保存结果: {batch_results}")
        
    except Exception as e:
        logger.error(f"程序执行错误: {e}")

if __name__ == '__main__':
    main()